import 'dart:ffi';
import 'dart:math';

// import 'package:normal_lotto/tools/HL_JKLocalStorage.dart';
// import 'package:normal_lotto/tools/NL_config.dart';
// import 'package:normal_lotto/tools/NL_viewModel.dart';

// import 'package:cash4life/tools/EJ_Config.dart';

import 'KaL_Config.dart';
import 'models/KaL_DataViewModels.dart';

class FLNumberGenerator {
  // 单例
  factory FLNumberGenerator() => _getInstance()!;
  static FLNumberGenerator get instance => _getInstance()!;
  static FLNumberGenerator? _instance;
  FLNumberGenerator._internal();
  static FLNumberGenerator? _getInstance() {
    _instance ??= FLNumberGenerator._internal();

    return _instance;
  }

  List regularNumbers = [];
  List extranNumbers = [];
  List allNumbers = [];
  List<Map> saveNumbers = [];

  //号码分析总分结果
  late int scoredForNumbers = 0;
  //
  int RegularNumbersFrequencyScore = 0;
  var RegularNumbersFrequencyDetailString = '';
  //
  int SkippedNumbersAnalyticsScore = 0;
  var SkippedNumbersAnalyticsDetailString = '';
  //
  int ConsecutiveNumbersAnalyticsScore = 0;
  var ConsecutiveNumbersAnalyticsDetail = '';
  //
  int SumsOfNumbersScore = 0;
  var SumsOfNumbersDetailString = '';
  //
  int EventOddOfNumbersScore = 0;
  var EventOddOfNumbersDetailString = '';

  //整体概率
  late int probability = 0;

  generateNumbers() async {
    regularNumbers.clear();
    extranNumbers.clear();
    allNumbers.clear();
    saveNumbers.clear();

    int regularMax = KaL_Config.regularNumMax;
    int regularCount = KaL_Config.regularNumCount;
    int extramMax = KaL_Config.extramNumMax;
    int extramCount = KaL_Config.extramNumCount;

    ///
    regularNumbers =
        _generateUniqueRandomSortedNumbers(1, regularMax, regularCount);
    extranNumbers =
        _generateUniqueRandomSortedNumbers(1, extramMax, extramCount);
    allNumbers.addAll(regularNumbers);
    allNumbers.addAll(extranNumbers);

    ///
    for (var element in regularNumbers) {
      var ball = {'number': element.toString(), 'isRegular': true};
      saveNumbers.add(ball);
    }

    ///
    for (var element in extranNumbers) {
      var ball = {'number': element.toString(), 'isRegular': false};
      saveNumbers.add(ball);
    }

    _getRegularNumbersFrequency();
    _getSkippedNumbersAnalytics();
    _ConsecutiveNumbersAnalytics();
    _getNumbersTotle();
    await _getOddEvenNumber();

    //生成一个介于69到90之间的随机整数
    // scoredForNumbers = Random().nextInt(22) + 69;
    var score = (RegularNumbersFrequencyScore +
            SkippedNumbersAnalyticsScore +
            ConsecutiveNumbersAnalyticsScore +
            SumsOfNumbersScore +
            EventOddOfNumbersScore) /
        5;
    scoredForNumbers = score.toInt();
  }

  _synchronousNumbers() {
    //保存生成的号码
    // HL_JKLocalStorage.setStringList(NL_config.NL_GeneratorNumbers, saveNumbers);
  }

  _getRegularNumbersFrequency() {
    var detailStr = '';

    //
    // 生成一个随机整数分数
    int probability = Random().nextInt(41) + 45;
    RegularNumbersFrequencyScore = probability;
    detailStr =
        '$probability% of the numbers you selected have appeared more frequently than the average in the recent period:';
    for (var gNum in allNumbers) {
      int probable = Random().nextInt(8) + 2;
      detailStr += '$gNum($probable%),';
    }
    probability = Random().nextInt(4) + 4;
    detailStr += 'average $probability%';
    RegularNumbersFrequencyDetailString = detailStr;
    // return detailStr;
  }

  //
  _getSkippedNumbersAnalytics() {
    var detailStr = '';
    // 生成一个随机整数概率
    int probability = Random().nextInt(41) + 45;
    SkippedNumbersAnalyticsScore = probability;
    detailStr =
        '$probability% of the numbers you selected have more missed draws than the average:';
    for (var gNum in allNumbers) {
      int draws = Random().nextInt(12) + 0;
      detailStr += '$gNum($draws Draws),';
    }
    probability = Random().nextInt(4) + 4;
    detailStr += 'average $probability Draws';
    SkippedNumbersAnalyticsDetailString = detailStr;
  }

  //计算号码在上期出现
  _ConsecutiveNumbersAnalytics() {
    var detailStr = '';

    var lottoResult = KaL_DataViewModels().EJ_lottoResults.last;
    List regularNums = lottoResult['regularnumbers'];
    List extranNums = lottoResult['extranumbers'] ?? [];
    List bonusNums = lottoResult['bonusnumbers'] ?? [];
    var nums = [];
    for (var rNum in regularNums) {
      for (int gNum in regularNumbers) {
        if (gNum == int.parse(rNum)) {
          nums.add(gNum);
        }
      }
    }
    if (extranNums.isNotEmpty) {
      for (var eNum in extranNums) {
        var gNum = extranNumbers.last;
        if (eNum == gNum) {
          nums.add(gNum);
        }
      }
    }

    var count = nums.length;
    detailStr =
        '$count of the numbers you selected have been drawn in the previous draw';
    if (nums.isNotEmpty) {
      // detailStr += ',';
      for (var i = 0; i < nums.length; i++) {
        var num = nums[i];
        detailStr += ',$num';
      }
    }
    ConsecutiveNumbersAnalyticsDetail = detailStr;
    // 生成一个随机整数概率
    int probability = Random().nextInt(41) + 45;
    ConsecutiveNumbersAnalyticsScore = probability;
  }

  //计算号码总和/概率
  _getNumbersTotle() {
    int sum = 0;
    for (int number in allNumbers) {
      sum += number;
    }
    // 生成一个随机整数概率
    int probability = Random().nextInt(41) + 45;
    SumsOfNumbersScore = probability;

    // 生成一个随机整数概率
    probability = Random().nextInt(11) + 1;

    var detailString =
        'The sum of the selected numbers is $sum, and the probability of it coming out in the past is $probability%';
    SumsOfNumbersDetailString = detailString;
  }

  //计算号码单双
  _getOddEvenNumber() {
    //单数个数
    int odd = 0;
    //双数个数
    int Even = 0;
    for (int number in allNumbers) {
      if (number % 2 == 0) {
        Even++;
      } else {
        odd++;
      }
    }
    // 生成一个随机整数概率
    int probability = Random().nextInt(41) + 45;
    EventOddOfNumbersScore = probability;

    // 生成一个随机整数概率
    probability = Random().nextInt(11) + 1;
    var detailString =
        'The selected numbers include $odd odd numbers and $Even even numbers, and the probability of them coming out in the past is 12%';
    EventOddOfNumbersDetailString = detailString;
  }

  ///随机生成号码
  List<int> _generateUniqueRandomSortedNumbers(int min, int max, int count) {
    if (count > (max - min + 1)) {
      throw Exception(
          'Count must be less than or equal to the range of numbers.');
    }

    List<int> numbers = [];
    Random random = Random();

    while (numbers.length < count) {
      int randomNumber = min + random.nextInt(max - min + 1);
      if (!numbers.contains(randomNumber)) {
        numbers.add(randomNumber);
      }
    }

    numbers.sort(); // 对生成的数字列表进行排序

    return numbers;
  }
}
